const EggService = require('egg').Service

class Service extends EggService {
  // 同步数据
  async syncData(options = {}) {
    const { ctx } = this
    const { helper } = ctx
    const { data } = options

    await helper.batchProcess(
      async (lastItem, batchSize) => {
        const filter = {
          ...options.filter,
        }

        if (lastItem) filter._id = { $gt: lastItem._id }

        return await options.model.find(filter).limit(batchSize)
      },
      async (docs) => {
        await helper.queue(docs, async (doc) => {
          options.keys.forEach((key) => {
            doc[key] = data[key]
          })
          await doc.save()
        })
      }
    )
  }
}

module.exports = Service
